home *** CD-ROM | disk | FTP | other *** search
- Path: fc.hp.com!not-for-mail
- From: neutron@fc.hp.com (Jack Applin)
- Newsgroups: comp.lang.c
- Subject: Re: gettimeofday() makes me mad !
- Date: 28 Feb 1996 20:23:29 GMT
- Organization: Hewlett-Packard, Ft. Collins, CO
- Distribution: inet
- Message-ID: <4h2dk1$e3i@fcnews.fc.hp.com>
- References: <4gnkth$4on@piston.ecp.fr>
- NNTP-Posting-Host: jackbert.fc.hp.com
- X-Newsreader: TIN [UNIX 1.3 310394BETA PL0]
-
- BIG ONE (dureta8@cti.ecp.fr) wrote:
-
- > PROBLEM : I'm trying to make a little program which must repeat an
- > action every .2 second for example ( less than 1 sec anyway). time()
- > wouldn't fit, so I searched and found the function gettimeofday() in
- > <sys/time.h>. It gives the time elapsed since 1970 in seconds and
- > microseconds. The problem is that when gettimeofday() is called several
- > times, it finally hangs up ! My program looks like this :
- >
- > struct timeval t ;
- > long useconds ;
- >
- > gettimeofday(&t) ;
- > printf("%ld\n",(usecondes = t.tv_usec)) ;
- >
- > for (;;) {
- > /* ... */ /*this part works fine */
- > gettimeofday(&t) ;
- > if (t.tv_usec > usecondes + 200000) {
- > printf("%ld\n",(usecondes = t.tv_usec)) ;
- > do_smthg() ;
- > }
- > }
-
-
- Your problem is that you're only looking at the microseconds. You have to compare
- both the seconds (tv_sec) and the microseconds (tv_usec) to the previous time.
- Here's a cheap way of doing it using floating-point arithmetic:
-
- #include <stdio.h>
- #include <time.h>
-
- main()
- {
- struct timeval t ;
- double previous, now;
-
- gettimeofday(&t) ;
-
- previous = t.tv_sec + t.tv_usec / 1000000.0; /* get a floating-point time */
-
- for (;;) {
- /* ... */ /*this part works fine */
- gettimeofday(&t) ;
- now = t.tv_sec + t.tv_usec / 1000000.0;
- if (now > previous + 0.2) {
- previous = now;
- puts("hi");
- }
- }
- }
-
- This may be inefficient, because it uses floating-point arithmetic,
- but it works. Another way would be to compare both the seconds and the
- microseconds of the times, like this:
-
- /* UNTESTED CODE */
- main()
- {
- struct timeval previous, now;
- long diff;
-
- gettimeofday(&previous) ;
-
- for (;;) {
- /* ... */ /*this part works fine */
- gettimeofday(&now) ;
- diff = (now.tv_sec - previous.tv_sec)*1000000
- +(now.tv_usec - previous.tv_usec);
- if (diff > 2000000) {
- previous = now;
- puts("hi");
- }
- }
- }
-
-
-
- -Jack Applin
- neutron@fc.hp.com
- http://www.cs.colostate.edu/~heckendo/Jack/
-